package coder.nav.sdk;

import coder.nav.model.bo.NavIdeRunBO;
import coder.nav.model.vo.NavIdeRunVO;
import coder.nav.utils.HttpUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Component
public class CoderRunAPI {

    @Value("${run-code-api}")
    private String runCodeApi;

    public NavIdeRunVO run(NavIdeRunBO bo) {
        Map<String, Object> params = new HashMap<>();
        params.put("memory", "10MB");
        params.put("timeout", "10");
        params.put("lang", bo.getLang());
        params.put("code", bo.getCode());
        params.put("input", bo.getInput());
        String response = HttpUtils.sendPostRequest(runCodeApi, params);
        // 字符编码转换 ISO_8859_1 -> UTF_8
        if(StringUtils.isNotBlank(response)) {
            byte[] bytes = response.getBytes(StandardCharsets.ISO_8859_1);
            response = new String(bytes, StandardCharsets.UTF_8);
        }
        return JSON.toJavaObject(JSON.parseObject(response), NavIdeRunVO.class);
    }

}
